//徐先生
const express = require("express");

var router = express.Router();

const db = require("../model/db.js");

//添加
router.post("/add", async (req, res) => {
 
    const data = await db.Goods.create(req.body)
    res.send({
        "code": 1,
        "msg": "10",
        "count": 0,
        "data": data
    })
})

//查询所有的
router.get("/all", async (req, res) => {
    let condition={}
    if (req.query.key) {
        let exp = new RegExp(req.query.key, "i")//不区分大小写，模糊查询正则表达式
        condition = {
            $or: [
                { nickname: { $regex: exp } },   //货品名字
                { category: { $regex: exp } } //类别
            ]
        }
    }
    let page = parseInt(req.query.page);
    let limit = parseInt(req.query.limit);
    let field = parseInt(req.query.field);
    // let sortB = parseInt(req.query.sort);
    if (!page) {
        page = 1;
    }
    if (!limit) {
        limit = 10
    }
    if (!field) {
        field = 1;
    }
    // if (!sortB) {
    //     sortB = "_id"
    // }
    const data = await db.Goods.find(condition).sort({"_id":field}).skip((page - 1) * limit).limit(limit);
    const count = await db.Goods.countDocuments();
    res.send({
        "code": 1,
        "msg": "10",
        "count": count,
        "data": data
    })
})
//删除
router.delete("/:id", async (req, res) => {
   
    const data= await db.Goods.deleteOne({ _id: req.params.id }) ;
    res.send({
        "code": 1,
        "msg": "10",
        "count": 0,
        "data": data
    })
})
//查询单个的
router.get("/:id", async (req, res) => {
   
    const data = await db.Goods.findById({ _id: req.params.id });
    res.send({
        "code": 1,
        "msg": "10",
        "count": 0,
        "data": data
    })
})
router.put("/:id", async (req, res) => {
   
    const data= await db.Goods.updateOne(//条件对象
        { _id: req.params.id }, req.body)
    res.send({
        "code": 1,
        "msg": "10",
        "count": 0,
        "data": data
    })
})
//得到供应商
router.get("/", async (req, res) => {
    const data = await db.Supplier.find({ supplierId: req.query.sid })
    const count=await db.Supplier.countDocuments({ supplierId: req.query.sid })
    res.send({
        "code": 0,
        "msg": "",
        "count": count,
        "data": data
    });
})
module.exports = router;